package com.app.miwawa.cui.system;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.framework.common.api.entity.CommonEntityAware;
import org.framework.common.api.service.bo.CommonBoAware;
import org.framework.common.api.support.model.FormModel;
import org.framework.common.api.support.model.QueryModel;
import org.framework.common.cui.AbstractController;
import org.framework.common.ext.exception.CommonException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.app.miwawa.api.system.service.bo.AssetsBo;

/**
 * 资源控制器类
 * <p>描述: </p>
 * <p>Company: Professional</p>
 * @author chanlong(陈龙)
 * @date 2016年1月13日 下午3:30:30
 * @version 1.0.2016
 */
@RestController
public class AssetsController extends AbstractController {

	private Logger log = Logger.getLogger(AssetsController.class);
	
	@Autowired
	private AssetsBo assetsBo;

	@Resource(name = "defaultBo")
	protected CommonBoAware<CommonEntityAware<String>, String> bo;
	
	@RequestMapping("/system/assets/{groupsid}/tree.json")
	public Object tree(@PathVariable final String groupsid, @ModelAttribute final QueryModel model) throws Exception {
		try{
			// 注册数据源
			registerDataSource(null);
			
			// 查询树结构数据
			return assetsBo.tree(groupsid, model);
		} catch (Exception e) {
			e.printStackTrace();
			throw new CommonException(log, "查询实体对象失败！");
		}
	}
	
	@RequestMapping("/system/assets/{groupsid}/update")
	public Object update(@PathVariable final String groupsid, @ModelAttribute final FormModel model) throws Exception {
		try{
			// 注册数据源
			registerDataSource(null);
			
			// 删除已绑定的资源
			assetsBo.deleteAuths(groupsid);
			
			// 获取实体对象
			List<CommonEntityAware<String>> entities = model.getEntities();

			// 保存实体对象
			if(entities != null && !entities.isEmpty()){
				return bo.insertAll(entities);
			}else{
				CommonEntityAware<String> entity = model.getEntity();
				return bo.insert(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new CommonException(log, "查询实体对象失败！");
		}
	}
}
